<template>
  <view class="tupu-content" ref="chartContainer">
    <!-- 使用renderjs -->
    <view :prop="option" :change:prop="echarts.update" class="echarts" id="echarts"></view>

    <!-- 自定义弹框 -->
    <view v-if="popupVisible&&group==1" class="custom-popup" :style="{ left: 0 + 'px', top: 100 + StatusBarRpx + 'rpx' }">
      <view class="title">{{ kuangObj.name }}</view>
      <view class="number-outer">
        关联资源：
        <text style="margin-right: 60rpx">{{ kuangObj.ziyuan }}</text>
        关联习题：
        <text>{{ kuangObj.xiti }}</text>
      </view>
      <view class="operate">
        学习进度：
        <text style="font-weight: bold; font-size: 28rpx; color: #31ca91">{{ kuangObj.rate }}%</text>
        <text class="go-sch" @click="goNext">去学习 ></text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    aid: String,
    nameTitle: String,
    course: String,
  },
  data() {
    return {
      option: {
        color: [],
        series: [
          {
            name: '知识图谱',
            type: 'graph',
            layout: 'force',
            force: {
              repulsion: 260,
              edgeLength: [80, 200],
              gravity: 0.1,
            },
            nodeScaleRatio: 0.6,
            draggable: true,
            roam: true,
            symbol: 'circle',
            data: [],
            links: [],
            focusNodeAdjacency: true,
            scaleLimit: {
              min: 0.5,
              max: 9,
            },
            edgeSymbol: ['circle'],
            edgeSymbolSize: [4, 8],
            label: {
              show: true,
              position: 'right',
              color: '#fff',
              distance: 5,
              fontSize: 10,
            },
            lineStyle: {
              width: 1.5,
              curveness: 0,
              type: 'solid',
            },
          },
        ],
      },
      popupVisible: false,
      popupPosition: {
        x: 0,
        y: 0,
      },
      kuangObj: {
        rate: '',
        xiti: '',
        ziyuan: '',
        name: '',
        aid: '',
      },
      colors: [
        {
          c1: '#145EFD',
          c2: '#4B8AFF',
        },
        {
          c1: '#31CA91',
          c2: '#5EE0B3',
        },
        {
          c1: '#FFB800',
          c2: '#FFD152',
        },
        {
          c1: '#FF7D00',
          c2: '#FF9D3F',
        },
        {
          c1: '#EE3B3B',
          c2: '#FF6B6B',
        },
        {
          c1: '#8A2BE2',
          c2: '#A569BD',
        },
        {
          c1: '#1E90FF',
          c2: '#6495ED',
        },
        {
          c1: '#3CB371',
          c2: '#2E8B57',
        },
      ],
    }
  },
  computed:{
    group(){
      return uni.getStorageSync('USER_GROUP');
    }
  },
  mounted() {
    this.get_textbookchapter_info()
  },
  methods: {
    async get_textbookchapter_info() {
      console.log(this.course)
      let res = await this.$api.post(global.apiUrls.post6900848db70d8, {
        textbookchapter_id: this.aid,
        course_id: this.course,
      })

      if (res.data.code == 1) {
        let arrs = res.data.data.data
        // res.data.data.children.map(item=>{
        // 	if(item.aid==this.id){
        // 		arrs=item.children
        // 	}
        // })
        console.log(this.nameTitle)
        // arrs.map(item=>{
        // 	=item.title
        // })
        const arr = [
          {
            title: this.nameTitle,
            value: this.nameTitle,
            children: arrs,
          },
        ]

        // 处理数据
        const legendColor = this.colors.map((item) => item.c2)
        const { nodes, links } = this.processData(arr)

        this.option.color = legendColor
        this.option.series[0].data = nodes
        this.option.series[0].links = links
      }
    },

    processData(arr, idx = 0, category = null) {
      const nodes = []
      const links = []

      const process = (data, level = 0) => {
        data.forEach((item) => {
          // 节点大小
          let symbolSize = 80
          if (level == 0) symbolSize = 130
          else if (item.is_zhishidian) symbolSize = 80
          else symbolSize = 100

          // 节点图标
          let symbol = 'circle'
          if (level == 0) {
            symbol = 'image://static/img02/zhang.png'
          } else if (item.is_zhishidian) {
            if (item.rate == 0) {
              symbol = 'image://static/img02/dian0.png'
            } else if (item.rate == 100) {
              symbol = 'image://static/img02/dian100.png'
            } else {
              symbol = 'image://static/img02/dian.png'
            }
          } else {
            symbol = 'image://static/img02/jie.png'
          }

          // 节点数据
          nodes.push({
            name: item.title,
            value: item.aid,
            symbolSize,
            symbol,
            category,
            title: item.title,
            aid: item.aid,
            is_zhishidian: item.is_zhishidian,
            category_name:item.cognitive_level_name,
            label: {
              show: true,
              position: 'inside',
              formatter: this.wrapText(item.title, symbolSize),
              fontSize: 11,
              lineHeight: 14,
              color: '#fff',
            },
          })

          // 处理子节点
          if (item.children) {
            item.children.forEach((child) => {
              links.push({
                source: item.title,
                target: child.title,
                lineStyle: {
                  color: 'rgba(57, 81, 129, 1)',
                },
              })
              process([child], level + 1)
            })
          }
        })
      }

      process(arr)
      return {
        nodes,
        links,
      }
    },

    // 文本换行处理
    wrapText(text, symbolSize, fontSize = 12) {
      const maxChars = Math.floor((symbolSize * 0.5) / (fontSize * 0.6))
      const lines = []
      for (let i = 0; i < text.length; i += maxChars) {
        lines.push(text.slice(i, i + maxChars))
      }
      return lines.join('\n')
    },

    // 跳转到知识点
    goNext() {
      this.$urouter.navigateTo(`/pages/course/knowledgePoints/knowledgePoints?aid=${this.kuangObj.aid}&kcid=${this.course}`)
    },

    // 处理节点点击事件
    handleNodeClick(data) {
      this.kuangObj = {
        name: data.name,
        aid: data.aid,
        rate: '',
        xiti: '',
        ziyuan: '',
      }

      // 计算弹窗位置
      // this.popupPosition = this.calculatePopupPosition(data.event);

      // 获取知识点详情
      this.get_zhishidian_infoApi(data.aid)
    },

    // 获取知识点详情
    async get_zhishidian_infoApi(aid) {
      this.popupVisible = true
      console.log(this.popupVisible);
      let res = await this.$api.post(global.apiUrls.post680ef68106993a1c62, {
        aid,
      })
      if (res.data.code == 1) {
        this.kuangObj = {
          ...res.data.data,
          name: this.kuangObj.name,
          aid: this.kuangObj.aid,
        }
      }
    },

    // 处理点击位置计算
    calculatePopupPosition(event) {
      const systemInfo = uni.getSystemInfoSync()
      const windowWidth = systemInfo.windowWidth
      const windowHeight = systemInfo.windowHeight

      // 获取图表容器的位置信息
      const query = uni.createSelectorQuery().in(this)
      query
        .select('.echarts')
        .boundingClientRect((data) => {
          const chartRect = data

          // 弹窗尺寸（px）
          const popupWidth = 236 // 472rpx / 2
          const popupHeight = 135 // 270rpx / 2

          // 计算点击位置相对于图表容器的坐标
          let clickX = event.clientX - chartRect.left
          let clickY = event.clientY - chartRect.top

          // 计算弹窗位置（确保不会超出图表容器边界）
          let popupX = clickX + 10
          let popupY = clickY + 10

          // 检查右边界
          if (popupX + popupWidth > chartRect.width) {
            popupX = clickX - popupWidth - 10
          }

          // 检查下边界
          if (popupY + popupHeight > chartRect.height) {
            popupY = clickY - popupHeight - 10
          }

          // 确保位置不小于0
          popupX = Math.max(0, popupX)
          popupY = Math.max(0, popupY)

          // 转换为相对于页面的绝对位置
          this.popupPosition = {
            x: popupX + chartRect.left,
            y: popupY + chartRect.top,
          }
        })
        .exec()

      // 返回一个默认位置，实际位置会在回调中更新
      return {
        x: event.clientX,
        y: event.clientY,
      }
    },
  },
}
</script>

<script module="echarts" lang="renderjs">
	import * as echarts from 'echarts';
	let chart = null;

	export default {
		mounted() {
			this.init();
			// if (typeof window.echarts === 'function') {

			// } else {
			// 	const script = document.createElement('script');
			// 	script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js';
			// 	script.onload = this.init;
			// 	document.head.appendChild(script);
			// }
		},
		methods: {
			handlePopupVisible(visible) {
        console.log(visible,'3333333333333');
				this.$nextTick(() => {
					this.popupVisible = visible;
				})
			},
			init() {
				chart = echarts.init(document.getElementById('echarts'));
				this.update(this.option);

				// 点击事件处理
				chart.on('click', (params) => {
					console.log('7777777777777777', params);
					if (!params.data || !params.data.category_name) {
						this.$ownerInstance.callMethod('handlePopupVisible', false);
						return;
					}

					// 传递点击数据给Vue组件
					this.$ownerInstance.callMethod('handleNodeClick', {
						name: params.data.title,
						aid: params.data.value,
						event: params.event.event
					});
				});
			},
			update(newOption) {
				if (chart) chart.setOption(newOption);
			},
			resize() {
				if (chart) chart.resize();
			}
		}
	};
</script>

<style scoped>
.tupu-content {
  height: 100%;
  width: 100%;
  position: relative;
}

.echarts {
  width: 100%;
  height: 100%;
  min-height: 600rpx;
  position: relative;
}

.custom-popup {
  position: fixed;
  width: 472rpx;
  height: 270rpx;
  background: linear-gradient(180deg, #cee0ff 0%, #ffffff 37%, #ffffff 100%);
  border-radius: 12rpx;
  border: 1rpx solid #eeeeee;
  z-index: 999;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  transform: translateZ(0);
  /* 解决某些浏览器下的渲染问题 */
}

.title {
  font-weight: 600;
  font-size: 30rpx;
  color: #131d34;
  margin-top: 24rpx;
  margin-left: 32rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 400rpx;
}

.number-outer {
  margin-top: 42rpx;
  margin-left: 32rpx;
  font-size: 26rpx;
  color: #747e96;
}

.operate {
  margin-top: 47rpx;
  margin-left: 32rpx;
  font-size: 26rpx;
  color: #747e96;
  display: flex;
  align-items: center;
}

.go-sch {
  display: inline-block;
  width: 140rpx;
  height: 48rpx;
  background: #145efd;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #ffffff;
  line-height: 48rpx;
  text-align: center;
  margin-left: 40rpx;
  cursor: pointer;
}
</style>